package logger

import (
	"bluebell/settings"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/natefinch/lumberjack" // 切割日志
	"go.uber.org/zap"                 // 日志库
	"go.uber.org/zap/zapcore"         // 日志库
	"net"
	"net/http"
	"net/http/httputil"
	"os"
	"runtime/debug"
	"strings"
	"time"
)

var logger *zap.Logger

func Init(cfg *settings.LogConfig, mode string) (err error) {
	writeSyncer := getLogWriter( // 配置日志输出文件
		cfg.Filename,
		cfg.MaxSize,
		cfg.MaxBackups,
		cfg.MaxAge,
	)
	encoder := getEncoder()                                   // 配置日志输出格式
	var l = new(zapcore.Level)                                // 定义日志级别(根据字符串判定日志级别)
	if err = l.UnmarshalText([]byte(cfg.Level)); err != nil { // 解组文本编码值UnmarshalText()
		fmt.Printf("UnmarshalText failed, %s\n", err)
	}

	var core zapcore.Core
	if mode == "dev" { // 开发模式,终端输出日志
		consoleEncoder := zapcore.NewConsoleEncoder(zap.NewDevelopmentEncoderConfig())
		core = zapcore.NewTee( // NewTee可以配置多个输出
			zapcore.NewCore(encoder, writeSyncer, l),                                     // 日志核心参数(编码格式, 写入文件, 日志级别)
			zapcore.NewCore(consoleEncoder, zapcore.Lock(os.Stdout), zapcore.DebugLevel), // 终端输出日志
		)
	} else {
		core = zapcore.NewCore(encoder, writeSyncer, l) // 日志核心参数(编码格式, 写入文件, 日志级别)
	}
	logger = zap.New(core, zap.AddCaller()) // 自定义日志库(使用参数配置)
	zap.ReplaceGlobals(logger)              // 注册全局的单例的logger
	return
}

func getEncoder() zapcore.Encoder {
	zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()) // 使用JSON编码格式
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder // 更改日志类型名称为大写
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder   // 更改时间显示格式
	return zapcore.NewConsoleEncoder(encoderConfig)         // 使用Console编码格式
}

func getLogWriter(filename string, maxSize int, maxBackup int, maxAge int) zapcore.WriteSyncer {
	lumberJackLogger := &lumberjack.Logger{ // 使用lumberjack进行日志切割归档
		Filename:   filename,
		MaxSize:    maxSize,   // 文件最大占用空间(M),超出大小后会将日志文件归档处理(文件名+时间格式重命名)
		MaxBackups: maxBackup, // 最大备份数量
		MaxAge:     maxAge,    // 最大备份天数
		Compress:   false,     // 是否压缩
	}
	return zapcore.AddSync(lumberJackLogger)
}

// GinLogger 定义gin实例日志库中间件
func GinLogger() gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		path := c.Request.URL.Path
		query := c.Request.URL.RawQuery
		c.Next()

		cost := time.Since(start)
		logger.Info(
			path,
			zap.Int("status", c.Writer.Status()),
			zap.String("method", c.Request.Method),
			zap.String("path", path),
			zap.String("query", query),
			zap.String("ip", c.ClientIP()),
			zap.String("user-agent", c.Request.UserAgent()),
			zap.String("errors", c.Errors.ByType(gin.ErrorTypePrivate).String()),
			zap.Duration("cost", cost),
		)
	}
}

// GinRecovery 定义gin实例日志库还原中间件
func GinRecovery(stack bool) gin.HandlerFunc {
	return func(context *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				var brokenPipe bool
				if ne, ok := err.(*net.OpError); ok {
					if se, ok := ne.Err.(*os.SyscallError); ok {
						if strings.Contains(strings.ToLower(se.Error()), "broken pipe") || strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") {
							brokenPipe = true
						}
					}
				}

				httpRequest, _ := httputil.DumpRequest(context.Request, false)
				if brokenPipe {
					logger.Error(
						context.Request.URL.Path,
						zap.Any("error", err),
						zap.String("request", string(httpRequest)),
					)
					_ = context.Error(err.(error))
					context.Abort()
					return
				}

				if stack {
					logger.Error(
						"[Recovery from panic]",
						zap.Any("error", err),
						zap.String("request", string(httpRequest)),
						zap.String("stack", string(debug.Stack())),
					)
				} else {
					logger.Error(
						"[Recovery from panic]",
						zap.Any("error", err),
						zap.String("request", string(httpRequest)),
					)
				}
				context.AbortWithStatus(http.StatusInternalServerError)
			}
		}()
	}
}
